package servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 石小俊
 * @date 2023年07月17日 9:15
 */
@WebServlet("/upload")
public class UploadServlet extends HttpServlet {
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        try {
            List<FileItem> fileItems = upload.parseRequest(request);
            Map<String,FileItem> items = new HashMap<>();
            for(FileItem item : fileItems){
                items.put(item.getFieldName(),item);
            }
            String path = getServletContext().getRealPath("/upload/"+new SimpleDateFormat("yyyyMMdd").format(new Date()));
            File f = new File(path);
            f.mkdirs();
            System.out.println("用户名:"+items.get("username").getString("utf-8"));
            FileItem file = items.get("file");
            file.write(new File(path,file.getName()));
            out.println("<span style='color:green'>恭喜您,上传成功</span>");
        } catch (FileUploadException e) {
            e.printStackTrace();
            out.println("<span style='color:red'>对不起,上传失败</span>");
        } catch (Exception e) {
            e.printStackTrace();
            out.println("<span style='color:red'>对不起,上传失败</span>");
        }
    }
}
